package io.renren.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.common.utils.R;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.entity.ImMessage;
import io.renren.modules.app.entity.Message;
import io.renren.modules.app.entity.SendInfo;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.FslipService;
import io.renren.modules.app.service.IImMessageService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.tio.StartTioRunner;
import io.renren.modules.app.tio.TioServerConfig;
import io.renren.modules.app.tio.WsOnlineContext;
import io.renren.modules.app.utils.ChatUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.server.ServerGroupContext;
import org.tio.websocket.common.WsResponse;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前端控制器
 *
 * @author 乐天
 * @since 2018-10-07
 */
@RestController
@RequestMapping("/app/user")
@Api("APP用户数据接口")
public class ImUserController {

    @Resource
    private StartTioRunner startTioRunner;

    @Resource
    @Qualifier(value = "userService")
    private UserService userService;

    @Resource
    @Qualifier(value = "fslipService")
    private FslipService fslipService;

    @Resource
    @Qualifier(value = "iImMessageService")
    private IImMessageService iImMessageService;

    /**
     * 用户信息初始化
     *
     * @param request request
     * @return json
     */
    @Login
    @RequestMapping("init")
    public R list(@LoginUser UserEntity user,HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<>();
        //获取好友信息
        objectMap.put("friends", fslipService.getUserFriends(user.getUserId().toString()));

        //获取本人信息
        String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", user.getNickname());
        user.setAvatar(host + user.getAvatar());
        user.setPassword(null);
        objectMap.put("me", user);

        //用户的群组信息
        objectMap.put("groups", userService.getChatGroups(user.getUserId().toString()));
        return R.ok().put("initData", objectMap);
    }


    /**
     * 获取群组的用户
     *
     * @param chatId 群组id
     * @return 用户List
     */
    @RequestMapping("chatUserList")
    public List<UserEntity> chatUserList(String chatId) {
        return userService.getChatUserList(chatId);
    }

    /**
     * 发送信息给用户
     * 注意：目前仅支持发送给在线用户
     * @param userId  接收方id
     * @param  msg 消息内容
     */
    @PostMapping("sendMsg")
    public void sendMsg(String userId, String msg,HttpServletRequest request) throws Exception {
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
        ServerGroupContext serverGroupContext = startTioRunner.getAppStarter().getWsServerStarter().getServerGroupContext();
        ChannelContext cc = WsOnlineContext.getChannelContextByUser(userId);
        SendInfo sendInfo = new SendInfo();
        sendInfo.setCode(ChatUtils.MSG_MESSAGE);
        Message message = new Message();
        message.setId("system");
        message.setFromid("system");
        message.setContent(msg);
        message.setMine(false);
        message.setTimestamp(System.currentTimeMillis());
        message.setType(ChatUtils.FRIEND);
        message.setAvatar(tempContextUrl + "/img/icon.png");
        message.setUsername("系统消息");
        //sendInfo.setMessage(message);
        if(cc!=null && !cc.isClosed){
            WsResponse wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo), TioServerConfig.CHARSET);
            Tio.sendToUser(serverGroupContext, userId, wsResponse);
        }else {
            saveMessage(message, ChatUtils.UNREAD,userId);
        }
    }

    private void saveMessage(Message message, String readStatus,String userId) {
        ImMessage imMessage = new ImMessage();
        imMessage.setToId(userId);
        imMessage.setFromId(message.getFromid());
        imMessage.setSendTime(System.currentTimeMillis());
        imMessage.setContent(message.getContent());
        imMessage.setReadStatus(readStatus);
        imMessage.setType(message.getType());
        iImMessageService.saveMessage(imMessage);
    }
}
